package com.zhaotianhao.controller;

import com.zhaotianhao.pojo.Users;
import com.zhaotianhao.service.UsersService;
import com.zhaotianhao.utils.RandomUtil;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.concurrent.TimeUnit;

/**
 * @Author Z-7
 * @Date 2022/3/4
 */
@Controller
@RequestMapping("user")
public class UserController {
    @DubboReference
    private UsersService usersService;
    @Resource
    private RedisTemplate redisTemplate;
    @GetMapping("login")
    public String to_login(){
        return "user/user_login";
    }
    @PostMapping("login")
    public String login(String username, String pwd, HttpServletRequest request){
        Users users = usersService.login(username,pwd);
        if(users == null){
            request.setAttribute("message","手机号或密码错误");
            return "user/user_login";
        }
        request.getSession().setAttribute("LOGIN_USER",users);
        return "redirect:../funds/list";
    }
    @RequestMapping("loginOut")
    public String loginOut(HttpSession session){
        session.invalidate();
        return "user/user_login";
    }
    @RequestMapping("to_register")
    public String to_register(){
        return "user/user_register";
    }
    @RequestMapping("register")
    public String register(Users users,String code,Model model){
        if(!(redisTemplate.hasKey(users.getUsername()))){
            model.addAttribute("error","请重新获取验证码");
            return "user/user_register";
        }
        String re_code = (String) redisTemplate.opsForValue().get(users.getUsername());
        if(re_code.equals(code)){
            int i = usersService.insert(users);
            if(i > 0){
                // 注册成功
                model.addAttribute("user",users);
                return "user/user_login";
            }
            model.addAttribute("error","注册失败");
            return "user/user_register";
        }
        model.addAttribute("error","验证码错误");
        return "user/user_register";
    }
    @RequestMapping("getCode")
    public @ResponseBody void getCode(String phone){
        String code = usersService.getCode();
        redisTemplate.opsForValue().set(phone,code,5,TimeUnit.MINUTES);
        System.out.println(code);
    }
    @RequestMapping("uniquePhone")
    public @ResponseBody boolean uniquePhone(String phone){
        Users users = usersService.getUser(phone);
        if(users == null){
            return true;
        }
        return false;
    }
}
